<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, inject } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { useMessage } from '@/hooks/web/useMessage';
  import { settingSchema } from './data';

  import { getConfigStorage, saveConfigStorage } from '@/api/app/setting';

  export default defineComponent({
    name: 'CloudSettingModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const tab_id: any = inject('tab_id');
      const { createMessage } = useMessage();

      // 配置表单
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 120,
        baseColProps: { span: 24 },
        schemas: settingSchema,
        showActionButtonGroup: false,
      });

      // 配置弹窗
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ minHeight: 1, canFullscreen: false, confirmLoading: false });
        setModalProps({ loading: true });
        const treeData = await getConfigStorage(tab_id.value);
        setTimeout(() => {
          treeData.type = tab_id.value;
          setFieldsValue(treeData);
          setModalProps({ loading: false });
        });
        updateSchema([
          {
            field: 'appid',
            ifShow: () => tab_id.value == 4,
          },
          {
            field: 'storageRegion',
            ifShow: () => tab_id.value == 5,
          },
        ]);
      });

      const getTitle = computed(() => '修改配置信息');

      // 提交表单
      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });

          await saveConfigStorage(values)
            .then(() => {
              createMessage.success('修改成功');
            })
            .catch(() => {});

          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
